﻿using System.Collections.Generic;
using System.Linq;
using roysland.net.xcom.core.DataAccess;
using roysland.net.xcom.core.Models;

namespace roysland.net.xcom.core.Helpers
{
    public class OBDataParser
    {
        private const int RecordLength = 54;

        public static List<ObDataRecord> GetRecords()
        {
            byte[] buffer = XComDataAccess.GetObData();
            var records = new List<ObDataRecord>();

            var counter = 1;
            for (int i = 0; i < 80; i++)
            {
                var offset = i * RecordLength;
                var buff = ByteHelper.GetByteSegment(offset, RecordLength, buffer);
                records.Add(new ObDataRecord(buff, counter));
                counter++;
            }
            return records;
        }

        public static void SaveObData(List<ObDataRecord> records)
        {
            byte[] buffer = XComDataAccess.GetObData();
            var list = from r in records
                       orderby r.RecordNumber ascending
                       select r;
            int counter = 0;
            foreach (var record in list)
            {
                var offset = counter * RecordLength;

                for (int i = 0; i < record.RecordBuffer.Length; i++)
                {
                    buffer[offset + i] = record.RecordBuffer[i];
                }
                counter++;
            }

            XComDataAccess.SetObData(buffer);
        }
    }
}
